<?php

namespace App\Module\Api\Controllers;

use App\Exceptions\Customize\ParamsException;
use App\Module\Api\Controllers\Request\ResetPasswordSubmitRequest;
use App\Module\Api\Validator\ResetPasswordSubmitValidator;
use App\System\Base\Repositories\BaseSmsCodeRepository;
use App\System\Cis\Repositories\CisUserRepository;
use Illuminate\Http\Request;


class ResetPasswordSubmitController extends Controller
{
    public function __construct()
    {
        $this->query=new ResetPasswordSubmitRequest();
        parent::__construct();
    }
    public function index(){
        (new ResetPasswordSubmitValidator())->check();
        $action = $this->query->action;
        $sms = BaseSmsCodeRepository::getInstance();
        $flag=$sms->verifyCode($this->query->smsId,$this->query->smsCode);
        $user = CisUserRepository::getInstance();
//        dd($flag);
        if ($flag['s'] !=0){
            return apiResponse($flag);
        }
        if ($action == 1){
//            忘记密码
//            根据smsid查询手机号
            $mobile =$sms->getMobile($this->query->smsId);
            $flag = $user->ModifyPassByMobile($mobile,$this->query->password);
            if (!$flag){
                throw new ParamsException([
                    'error_code' => '1000',
                    'message'    => '更改失败',
                ]);
            }
            return apiResponse(['d'=>'更改成功']);
        }
//            重置密码
        //判断当前用户有无登录
        $cache = \Cache::get(\request()->s);
        if (!isset($cache['userInfo'])){
            throw new ParamsException([
                'error_code' => '1000',
                'message'    => '用户未登录',
            ]);
        }
        $uid = $cache['userInfo']->id;

//        验证原密码
        $flag =$user->verifyCurrentPass($uid,$this->query->currentPass);
        if (!$flag){
            throw new ParamsException([
                'error_code' => '1000',
                'message'    => '原密码错误',
            ]);
        }
        $flag = $user->ModifyPassByUserId($uid,$this->query->password);
        if (!$flag){
            throw new ParamsException([
                'error_code' => '1000',
                'message'    => '修改失败',
            ]);
        }
        return apiResponse(['d'=>'修改成功']);
    }
}
